'use client';

import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { 
  Form, 
  Input, 
  Select, 
  Radio, 
  Checkbox, 
  Button, 
  Card, 
  Table, 
  Space,
  InputNumber
} from 'antd';
import type { RadioChangeEvent } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { 
  InstrumentConsumable, 
  InstrumentIncrementService, 
  OrderType, 
  FeeMethod, 
  TrainFeeMethod 
} from '@/types/instrument';
import { ORDER_TYPE_OPTIONS, FEE_METHOD_OPTIONS, TRAIN_FEE_METHOD_OPTIONS } from '@/constants/instrument';
import RichTextEditor from '@/components/RichTextEditor';

const { Option } = Select;

export interface ReservationSettingsRef {
  getFormData: () => Record<string, unknown>;
}

interface ReservationSettingsProps {
  form?: unknown;
  mode?: 'create' | 'edit' | 'view';
  initialValues?: Record<string, unknown>;
  onMinDurationChange?: (minDuration: number) => void;
}

const ReservationSettings = forwardRef<ReservationSettingsRef, ReservationSettingsProps>(({
  mode = 'create',
  initialValues = {},
  onMinDurationChange,
}, ref) => {
  const [form] = Form.useForm();
  const isReadOnly = mode === 'view';
  
  // 订单类型状态
  const [selectedOrderTypes, setSelectedOrderTypes] = useState<string[]>([]);
  // 培训收费方式状态
  const [trainingChargeMethod, setTrainingChargeMethod] = useState<TrainFeeMethod>(TrainFeeMethod.BY_HOUR);
  // 仪器收费方式状态
  const [instrumentChargeMethod, setInstrumentChargeMethod] = useState<FeeMethod>(FeeMethod.BY_HOUR);
  
  const [consumables, setConsumables] = useState<InstrumentConsumable[]>([]);
  const [services, setServices] = useState<InstrumentIncrementService[]>([]);

  useEffect(() => {
    // 初始化表单值
    if (initialValues.orderTypes) {
      const orderTypes = initialValues.orderTypes.toString().split(',').filter(Boolean);
      setSelectedOrderTypes(orderTypes);
    }
    if (initialValues.trainFeeMethod) {
      setTrainingChargeMethod(initialValues.trainFeeMethod as TrainFeeMethod);
    }
    if (initialValues.feeMethod) {
      setInstrumentChargeMethod(initialValues.feeMethod as FeeMethod);
    }
    if (initialValues.consumables) {
      setConsumables(initialValues.consumables as InstrumentConsumable[]);
    }
    if (initialValues.incrementServices) {
      setServices(initialValues.incrementServices as InstrumentIncrementService[]);
    }
    
    // 当 initialValues 变化时，更新表单字段值
    if (Object.keys(initialValues).length > 0) {
      form.setFieldsValue({
        ...initialValues,
        orderTypes: initialValues.orderTypes?.toString() || ''
      });
    }
  }, [initialValues, form]);

  // 处理订单类型变化
  const handleOrderTypesChange = (checkedValues: string[]) => {
    setSelectedOrderTypes(checkedValues);
    form.setFieldValue('orderTypes', checkedValues.join(','));
  };

  // 处理培训收费方式变化
  const handleTrainingChargeMethodChange = (e: RadioChangeEvent) => {
    const method = e.target.value as TrainFeeMethod;
    setTrainingChargeMethod(method);
    form.setFieldValue('trainFeeMethod', method);
  };

  // 处理仪器收费方式变化
  const handleInstrumentChargeMethodChange = (e: RadioChangeEvent) => {
    const method = e.target.value as FeeMethod;
    setInstrumentChargeMethod(method);
    form.setFieldValue('feeMethod', method);
  };

  // 添加耗材
  const handleAddConsumable = () => {
    const newConsumable: InstrumentConsumable = {
      name: '',
      price: 0,
      unit: '',
      isRequired: 0,
    };
    const newConsumables = [...consumables, newConsumable];
    setConsumables(newConsumables);
    form.setFieldValue('consumables', newConsumables);
  };

  // 添加服务
  const handleAddService = () => {
    const newService: InstrumentIncrementService = {
      name: '',
      price: 0,
      unit: '',
      isRequired: 0,
    };
    const newServices = [...services, newService];
    setServices(newServices);
    form.setFieldValue('incrementServices', newServices);
  };

  // 删除耗材
  const handleDeleteConsumable = (index: number) => {
    const newConsumables = consumables.filter((_, i) => i !== index);
    setConsumables(newConsumables);
    form.setFieldValue('consumables', newConsumables);
  };

  // 删除服务
  const handleDeleteService = (index: number) => {
    const newServices = services.filter((_, i) => i !== index);
    setServices(newServices);
    form.setFieldValue('incrementServices', newServices);
  };

  // 更新耗材
  const handleUpdateConsumable = (index: number, field: string, value: unknown) => {
    const newConsumables = [...consumables];
    newConsumables[index] = { ...newConsumables[index], [field]: value };
    setConsumables(newConsumables);
    form.setFieldValue('consumables', newConsumables);
  };

  // 更新服务
  const handleUpdateService = (index: number, field: string, value: unknown) => {
    const newServices = [...services];
    newServices[index] = { ...newServices[index], [field]: value };
    setServices(newServices);
    form.setFieldValue('incrementServices', newServices);
  };

  // 耗材表格列
  const consumableColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: InstrumentConsumable, index: number) => (
        <Input 
          value={text} 
          placeholder="请输入"
          disabled={isReadOnly}
          onChange={(e) => handleUpdateConsumable(index, 'name', e.target.value)}
        />
      ),
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      render: (text: string, record: InstrumentConsumable, index: number) => (
        <Input 
          value={text} 
          placeholder="请输入"
          disabled={isReadOnly}
          onChange={(e) => handleUpdateConsumable(index, 'unit', e.target.value)}
        />
      ),
    },
    {
      title: '单价（元）',
      dataIndex: 'price',
      key: 'price',
      render: (value: number, record: InstrumentConsumable, index: number) => (
        <InputNumber 
          value={value} 
          placeholder="请输入"
          disabled={isReadOnly}
          min={0}
          precision={2}
          onChange={(val) => handleUpdateConsumable(index, 'price', val || 0)}
        />
      ),
    },
    {
      title: '设置为必选后，默认数量为1且用户不可删除',
      key: 'actions',
      render: (_: unknown, record: InstrumentConsumable, index: number) => (
        <Space>
          <Checkbox 
            checked={record.isRequired === 1}
            disabled={isReadOnly}
            onChange={(e) => handleUpdateConsumable(index, 'isRequired', e.target.checked ? 1 : 0)}
          >
            必选项
          </Checkbox>
          {!isReadOnly && (
            <Button 
              type="link" 
              icon={<DeleteOutlined />}
              onClick={() => handleDeleteConsumable(index)}
            >
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 服务表格列
  const serviceColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: InstrumentIncrementService, index: number) => (
        <Input 
          value={text} 
          placeholder="请输入"
          disabled={isReadOnly}
          onChange={(e) => handleUpdateService(index, 'name', e.target.value)}
        />
      ),
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      render: (text: string, record: InstrumentIncrementService, index: number) => (
        <Input 
          value={text} 
          placeholder="请输入"
          disabled={isReadOnly}
          onChange={(e) => handleUpdateService(index, 'unit', e.target.value)}
        />
      ),
    },
    {
      title: '价格（元）',
      dataIndex: 'price',
      key: 'price',
      render: (value: number, record: InstrumentIncrementService, index: number) => (
        <InputNumber 
          value={value} 
          placeholder="请输入"
          disabled={isReadOnly}
          min={0}
          precision={2}
          onChange={(val) => handleUpdateService(index, 'price', val || 0)}
        />
      ),
    },
    {
      title: '设置为必选后，默认数量为1且用户不可删除',
      key: 'actions',
      render: (_: unknown, record: InstrumentIncrementService, index: number) => (
        <Space>
          <Checkbox 
            checked={record.isRequired === 1}
            disabled={isReadOnly}
            onChange={(e) => handleUpdateService(index, 'isRequired', e.target.checked ? 1 : 0)}
          >
            必选项
          </Checkbox>
          {!isReadOnly && (
            <Button 
              type="link" 
              icon={<DeleteOutlined />}
              onClick={() => handleDeleteService(index)}
            >
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    getFormData: () => {
      const formValues = form.getFieldsValue();
      return {
        ...formValues,
        // 确保包含耗材和增值服务数据
        consumables,
        incrementServices: services,
      };
    }
  }), [form, consumables, services]);

  return (
    <Form
      form={form}
      disabled={isReadOnly}
      initialValues={{
        orderTypes: '',
        trainFeeMethod: TrainFeeMethod.BY_HOUR,
        feeMethod: FeeMethod.BY_HOUR,
        leadTime: 12,
        minDuration: 30,
        trainFeeUnit: 60,
        feeUnit: 60,
        ...initialValues
      }}
    >
      <div style={{ maxWidth: '800px' }}>
        {/* 预约申请单 */}
        <Card title="预约申请单" style={{ marginBottom: 24 }}>
          <Form.Item
            label="预约申请单"
            name="appointForm"
            extra="老师上传文档，可在线编辑修改让用户填写"
          >
            <RichTextEditor
              placeholder="请输入或上传预约申请单内容"
              height={200}
              disabled={isReadOnly}
            />
          </Form.Item>
        </Card>

        {/* 可选订单类型 */}
        <Form.Item
          label="可选订单类型"
          name="orderTypes"
          rules={[{ required: true, message: '请至少选择一个订单类型' }]}
        >
          <Checkbox.Group 
            value={selectedOrderTypes}
            onChange={handleOrderTypesChange}
          >
            <div style={{ display: 'flex', gap: '8px' }}>
              {ORDER_TYPE_OPTIONS.map(option => (
                <Checkbox key={option.value} value={option.value}>
                  {option.label}
                </Checkbox>
              ))}
            </div>
          </Checkbox.Group>
        </Form.Item>

        {/* 送样申请预计交付时间 - 条件显示 */}
        {selectedOrderTypes.includes(OrderType.SAMPLE_DELIVERY) && (
          <Form.Item
            label="送样申请预计交付时间"
            name="deliveryTime"
            extra="例：7个工作日"
          >
            <Input placeholder="请输入" style={{ width: '400px' }} />
          </Form.Item>
        )}

        {/* 培训收费方式 - 条件显示 */}
        {selectedOrderTypes.includes(OrderType.SELF_OPERATION) && (
          <>
            <Form.Item
              label="培训收费方式"
              name="trainFeeMethod"
              extra="自主操作首次默认必须培训，用户首次实验类型固定为培训"
            >
              <Radio.Group 
                value={trainingChargeMethod}
                onChange={handleTrainingChargeMethodChange}
              >
                {TRAIN_FEE_METHOD_OPTIONS.map(option => (
                  <Radio key={option.value} value={option.value}>
                    {option.label}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>

            {trainingChargeMethod === TrainFeeMethod.BY_HOUR && (
              <>
                <Form.Item
                  label="培训计费单位"
                  name="trainFeeUnit"
                >
                  <InputNumber
                    min={1}
                    defaultValue={60}
                    addonAfter="分钟"
                    style={{ width: '200px' }}
                  />
                </Form.Item>

                <Form.Item
                  label="培训费用"
                  name="trainFee"
                >
                  <InputNumber
                    placeholder="请输入"
                    addonAfter="元/小时"
                    style={{ width: '300px' }}
                    min={0}
                    precision={2}
                  />
                </Form.Item>
              </>
            )}

            {trainingChargeMethod === TrainFeeMethod.BY_TIME && (
              <Form.Item
                label="培训费用"
                name="trainFee"
              >
                <InputNumber
                  placeholder="请输入"
                  addonAfter="元/次"
                  style={{ width: '300px' }}
                  min={0}
                  precision={2}
                />
              </Form.Item>
            )}
          </>
        )}

        {/* 仪器收费方式 */}
        <Form.Item
          label="仪器收费方式"
          name="feeMethod"
        >
          <Radio.Group 
            value={instrumentChargeMethod}
            onChange={handleInstrumentChargeMethodChange}
          >
            {FEE_METHOD_OPTIONS.map(option => (
              <Radio key={option.value} value={option.value}>
                {option.label}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>

        {instrumentChargeMethod === FeeMethod.BY_HOUR && (
          <>
            <Form.Item
              label="仪器计费单位"
              name="feeUnit"
            >
              <InputNumber
                min={1}
                defaultValue={60}
                addonAfter="分钟"
                style={{ width: '200px' }}
              />
            </Form.Item>

            <Form.Item
              label="单价"
              name="price"
              rules={[{ required: true, message: '请输入单价' }]}
            >
              <InputNumber
                placeholder="请输入"
                addonAfter="元/小时"
                style={{ width: '300px' }}
                min={0}
                precision={2}
              />
            </Form.Item>
          </>
        )}

        {instrumentChargeMethod === FeeMethod.BY_SAMPLE && (
          <Form.Item
            label="单价"
            name="price"
            rules={[{ required: true, message: '请输入单价' }]}
          >
            <InputNumber
              placeholder="请输入"
              addonAfter="元/样品"
              style={{ width: '300px' }}
              min={0}
              precision={2}
            />
          </Form.Item>
        )}

        {/* 预约提前时间和最小预约时长 */}
        <Form.Item
          label="预约提前时间"
          name="leadTime"
          rules={[{ required: true, message: '请输入预约提前时间' }]}
        >
          <InputNumber
            min={1}
            defaultValue={12}
            addonAfter="小时"
            style={{ width: '200px' }}
          />
        </Form.Item>

        <Form.Item
          label="最小预约时长"
          name="minDuration"
          rules={[
            { required: true, message: '请输入最小预约时长' },

          ]}
        >
          <InputNumber
            min={15}
            defaultValue={30}
            addonAfter="分钟"
            style={{ width: '200px' }}
            placeholder="请输入15的倍数"
            onChange={(value) => {
              if (value && onMinDurationChange) {
                onMinDurationChange(value);
              }
            }}
          />
        </Form.Item>

        {/* 选择耗材 */}
        <Card title="选择耗材" style={{ marginBottom: 24 }}>
          {!isReadOnly && (
            <div style={{ marginBottom: 16 }}>
              <Button 
                type="dashed" 
                icon={<PlusOutlined />}
                onClick={handleAddConsumable}
              >
                点击添加
              </Button>
            </div>
          )}
          <Table
            columns={consumableColumns}
            dataSource={consumables}
            pagination={false}
            size="small"
            rowKey={(record, index) => index?.toString() || '0'}
          />
        </Card>

        {/* 增值服务 */}
        <Card title="增值服务" style={{ marginBottom: 24 }}>
          {!isReadOnly && (
            <div style={{ marginBottom: 16 }}>
              <Button 
                type="dashed" 
                icon={<PlusOutlined />}
                onClick={handleAddService}
              >
                点击添加
              </Button>
            </div>
          )}
          <Table
            columns={serviceColumns}
            dataSource={services}
            pagination={false}
            size="small"
            rowKey={(record, index) => index?.toString() || '0'}
          />
        </Card>

        {/* 样品邮寄地址 */}
        <Card title="样品邮寄地址" style={{ marginBottom: 24 }}>
          <Form.Item
            label="收货姓名"
            name="consignee"
            rules={[{ required: true, message: '请输入收货姓名' }]}
          >
            <Input placeholder="请输入" style={{ width: '300px' }} />
          </Form.Item>

          <Form.Item
            label="收货电话"
            name="phone"
            rules={[{ required: true, message: '请输入收货电话' }]}
          >
            <Input placeholder="请输入" style={{ width: '300px' }} />
          </Form.Item>

          <div style={{ display: 'flex', gap: '16px', alignItems: 'center', marginBottom: '16px' }}>
            <Form.Item
              label="所在地区"
              name="provinceCode"
              rules={[{ required: true, message: '请选择省份' }]}
              style={{ marginBottom: 0 }}
            >
              <Select placeholder="省" style={{ width: '120px' }}>
                <Option value="110000">北京</Option>
                <Option value="310000">上海</Option>
                <Option value="440000">广东</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="cityCode"
              rules={[{ required: true, message: '请选择城市' }]}
              style={{ marginBottom: 0 }}
            >
              <Select placeholder="市" style={{ width: '120px' }}>
                <Option value="110100">北京市</Option>
                <Option value="310100">上海市</Option>
                <Option value="440100">广州市</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="districtCode"
              rules={[{ required: true, message: '请选择区县' }]}
              style={{ marginBottom: 0 }}
            >
              <Select placeholder="区" style={{ width: '120px' }}>
                <Option value="110105">朝阳区</Option>
                <Option value="110108">海淀区</Option>
                <Option value="110102">西城区</Option>
              </Select>
            </Form.Item>
          </div>

          <Form.Item
            label="详细地址"
            name="address"
            rules={[{ required: true, message: '请输入详细地址' }]}
          >
            <Input placeholder="请输入" style={{ width: '500px' }} />
          </Form.Item>
        </Card>
      </div>
    </Form>
  );
});

ReservationSettings.displayName = 'ReservationSettings';

export default ReservationSettings; 